package cn.sjx.modules.nbiot.factory;

import cn.sjx.modules.nbiot.entity.common.IotProtocolConstants;
import cn.sjx.modules.nbiot.entity.receive.IotProtocolReceive_0x20;
import cn.sjx.modules.nbiot.entity.receive.IotProtocolReceive_0x21;
import cn.sjx.modules.nbiot.entity.receive.IotProtocolReceive_0x78;
import cn.sjx.modules.nbiot.entity.receive.ReceiveBase;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import io.netty.buffer.ByteBuf;

import java.util.HashMap;
import java.util.Map;

/**
 * 数据接收类创建工厂
 * @author sjx
 */
public class ReceiveFactory {

    private static final Log logger = LogFactory.get();

    private static Map<Integer, Class<? extends ReceiveBase>> receiveMap = null;

    /**
     * 接收数据类型与实体类对应的map集合
     */
    static {
        receiveMap = new HashMap<Integer, Class<? extends ReceiveBase>>(2);

        receiveMap.put(IotProtocolConstants.GEOMAGNETIC_RECEIVING_STATE, IotProtocolReceive_0x20.class);
        receiveMap.put(IotProtocolConstants.GEOMAGNETIC_HEARTBEAT_PACKET, IotProtocolReceive_0x21.class);
        receiveMap.put(IotProtocolConstants.GEOMAGNETIC_RESPONSE_MESSAGE, IotProtocolReceive_0x78.class);
    }

    /**
     * 创建接收数据类
     *
     * @param type 报文类型
     * @param buf  数据包
     * @return
     */
    public static ReceiveBase createReceiveEntity(int type, ByteBuf buf) {

        // 根据业务获取普通报文接收类
        Class<? extends ReceiveBase> cls = receiveMap.get(type);

        try {
            if (null == cls) {
                throw new RuntimeException("不支持的应答数据");
            }

            ReceiveBase receiveBase = cls.newInstance();
            receiveBase.decode(buf);

            return receiveBase;
        } catch (RuntimeException re) {
            logger.debug("======> 【地磁|接收数据|实例化】：{}", re.getMessage());
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
        return null;
    }

}
